import Vue from 'vue'
import md5 from 'js-md5'
import moment from 'moment'
import { MessageBox, Message } from 'element-ui'

/**
 * confirm弹窗
 * @param {String} title 提示标题
 * @param {Boolean} type  主题
 * @param {String} message   消息文字
 * @param {Boolean} center    文字是否居中
 * @param {String} confirmButtonText  确认按钮文字
 * @param {String} cancelButtonText     取消按钮文字
 * @returns
 */
export function handleConfirm({
  title = '提示',
  type = 'warning',
  message,
  center = false,
  confirmButtonText = '确认',
  cancelButtonText = '取消'
}) {
  return MessageBox.confirm(message, title, {
    type,
    center,
    confirmButtonText,
    cancelButtonText
  })
}

/**
 * message提示
 * @param {String} message
 * @param {Boolean} type
 * @param {Boolean} showClose
 * @param {Boolean} center
 */
export function handleAlert({ message, type = 'success', showClose = 'true', center = 'false' }) {
  Message({ message, type, showClose, center })
}

/**
 * 去除对象中的空字段
 * @param obj
 * @returns {{}|*}
 */
export function removeObjEmptyKey(obj) {
  let keys = Object.keys(obj)
  let resultObj = {}
  if (keys) {
    keys.forEach(value => {
      if (obj[value]) {
        resultObj[value] = obj[value]
      }
    })
    return resultObj
  }
  return obj
}

/**
 * 获取当前位置的经纬度
 */
export function getlocationPosition() {
  let data = {
    key: 'IILBZ-UO5RJ-EWHFP-KMILG-SHY5Q-63BWX' //这个key就是你申请的密钥
  }
  let url = 'https://apis.map.qq.com/ws/location/v1/ip' //这个就是地理位置信息的接口
  data.output = 'jsonp'
  return Vue.prototype
    .$jsonp(url, data)
    .then(res => {
      if (res.status === 0) {
        const {
          ip,
          location: { lat, lng }
        } = res.result
        return {
          ip,
          lat,
          lng
        }
      }
    })
    .catch(error => {
      message.error(error)
    })
}

/**
 * 过滤实时刷新数据tabs(一个对象结构)
 * @param {*tabs配置项} tabs
 * @param {*源数据} data
 * @returns
 */
export function useFilterBaseStatistics(tabs, data) {
  return tabs.map(el => {
    return { ...el, value: data[el.key] }
  })
}

/**
 * 过滤实时刷新数据tabs
 * @param {*tabs配置项} tabs
 * @param {*源数据} data
 * @returns
 */
export function useFilterSingleStatistics(tabs, data) {
  return tabs.map(item => {
    for (const key in data) {
      if (item.baseData && key === item.baseData.key) {
        item.baseData.value = data[key]
      }
      if (item.yesterdayData && key === item.yesterdayData.key) {
        item.yesterdayData.value = data[key]
      }
    }
    return item
  })
}

/**
 * 过滤统计数据（有昨日数据）
 * @param {*Array} tabs
 * @param {*Array} data
 * @returns
 */
export function useFilterStatistics(tabs, data, flag = true) {
  const filterData = tabs.map(item => {
    if (item.yesterdayData) {
      item.yesterdayData.isShow = flag
    }
    for (const key in data) {
      if (item.prompt && item.prompt.isShow && item.prompt.key === key) {
        item.prompt.percentage = `${data[key]}%`
      }
      if (key === 'baseData') {
        for (const cKey in data[key]) {
          if (item.baseData && item.baseData.key) {
            if (cKey === item.baseData.key) {
              item.baseData.value = data[key][cKey]
            }
          }
        }
      }
      if (key === 'yesterdayData') {
        for (const cKey in data[key]) {
          if (item.yesterdayData && item.yesterdayData.key) {
            if (cKey === item.yesterdayData.key) {
              item.yesterdayData.value = data[key][cKey] === null ? '0' : data[key][cKey]
            }
          }
        }
      }
    }
    return item
  })
  return filterData
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 校验指向位置
 * @param {*Object} formData
 * @returns
 */
export function useValidatepointPlace(formData) {
  let flag
  if (formData.pointPlace === 0) {
    flag = true
  }
  if (!formData.targetParam) {
    if (formData.pointPlace === 1) {
      message.error('请选择指向栏目')
      flag = false
    } else if (formData.pointPlace === 2) {
      message.error('请选择指向分类')
      flag = false
    } else if (formData.pointPlace === 3) {
      message.error('请选择指向商品')
      flag = false
    } else if (formData.pointPlace === 4) {
      if (!formData.outsideType) {
        message.error('请选择指向平台')
        flag = false
      } else if (!formData.iconThreePoint) {
        message.error('请输入指向路径')
        flag = false
      } else {
        flag = true
      }
    }
  } else {
    flag = true
  }
  return flag
}

/**
 * 更改element-ui主体色
 * @param {*String} color
 */
export function usePrimaryColor(color) {
  const el = document.documentElement
  el.style.setProperty('--el-color-primary', color)
  const tempColors = color.split('#')[1]
  const r = parseInt('0x' + tempColors.slice(0, 2))
  const g = parseInt('0x' + tempColors.slice(2, 4))
  const b = parseInt('0x' + tempColors.slice(4, 6))
  for (let i = 1; i <= 9; i++) {
    el.style.setProperty('--el-color-primary-light-' + i, `rgba(${r}, ${g}, ${b}, ${1 - i * 0.1})`)
  }
}

/**
 * 生成唯一id
 * @return uuid
 */
export function useGenerateUUID() {
  var d = new Date().getTime()
  if (window.performance && typeof window.performance.now === 'function') {
    d += performance.now() //use high-precision timer if available
  }
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
  return uuid
}

/**
 * 创建随机字符串
 * @param num
 * @returns {string}
 */
export function useRandomString(num) {
  const chars = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z'
  ]
  let res = ''
  for (let i = 0; i < num; i++) {
    let id = Math.ceil(Math.random() * 35)
    res += chars[id]
  }
  return res
}

/**
 * 上传文件生成文件名称
 * @param {*} file
 * @returns
 */
export function setUpFileName(file) {
  const dateTime = moment(new Date()).format('YYYY-MM-DD hh:mm:ss') // 当前时间
  const randomStr = useRandomString(4) //  4位随机字符串
  let suffix = file.name.split('.')[file.name?.split('.').length - 1] // 获取文件后缀
  return md5(dateTime + randomStr) + '.' + suffix
}

/**
 * 重写el-element Message提示框
 */
const showMessage = Symbol('showMessage')
class DoneMessage {
  [showMessage](type, options, single) {
    if (single) {
      if (document.getElementsByClassName('el-message').length === 0) {
        Message[type](options)
      }
    } else {
      Message[type](options)
    }
  }
  info(options, single = true) {
    this[showMessage]('info', options, single)
  }
  warning(options, single = true) {
    this[showMessage]('warning', options, single)
  }
  error(options, single = true) {
    this[showMessage]('error', options, single)
  }
  success(options, single = true) {
    this[showMessage]('success', options, single)
  }
}
export const message = new DoneMessage()

/**
 * 下载图片
 * @param {String} name
 * @param {String} imgsrc
 */
export function downLoadImg(name, imgsrc) {
  //下载图片地址和图片名
  var image = document.createElement('img')
  image.src = imgsrc
  // 解决跨域 Canvas 污染问题
  image.setAttribute('crossOrigin', 'anonymous')
  image.onload = function () {
    var canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    var context = canvas.getContext('2d')
    context.drawImage(image, 0, 0, image.width, image.height)
    var url = canvas.toDataURL('image/png') //得到图片的base64编码数据
    var a = document.createElement('a') // 生成一个a元素
    var event = new MouseEvent('click') // 创建一个单击事件
    a.download = name || 'photo' // 设置图片名称
    a.href = url // 将生成的URL设置为a.href属性
    a.dispatchEvent(event) // 触发a的单击事件
  }
}
